import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_boost/flutter_boost.dart';
import 'package:t3_data_service/biz_data_source/map/address/city_pick/model/host_model.dart';
import 'package:t3_data_service/biz_data_source/map/address/poi_search/poi_search.dart';
import 'package:t3_map/data_report/address_log.dart';
import 'package:t3_track/t3_track.dart';
import 'package:uikit/uikit.dart';
import 'package:t3_foundation/t3_foundation.dart';
import '../../../configs/address_select_enums.dart';
import '../../../configs/poi_search_multi_points_config.dart';
import '../../model/const.dart';
import 'input_item.dart';
import '../../view_model/poi_search_bar_view_model.dart';
import '../../view_model/poi_search_cell_view_model.dart';
import 'input_item_widget.dart';

class T3MultiInputBoard extends StatefulWidget {
  final POISearchMultiPointsConfig searchConfig;
  final POISearchBarViewModel viewModel;
  final AirportCityChangeCallback airportCityChangeCallback;
  final ValueChanged<T3SearchCondition> onSearchConditionDidChanged;
  final ValueChanged<List<POISearchCellViewModel>> onFinishSelection;

  T3MultiInputBoard({
    super.key,
    required this.viewModel,
    required this.searchConfig,
    required this.airportCityChangeCallback,
    required this.onFinishSelection,
    required this.onSearchConditionDidChanged,
  });

  @override
  _T3MultiInputBoardState createState() => _T3MultiInputBoardState();
}

class _T3MultiInputBoardState extends State<T3MultiInputBoard> {
  final List<InputItem> inputItems = [];
  bool isActionBarHidden = true;
  bool isAddMidwayButtonEnabled = false;
  // 是否需要隐藏 添加途经点 按钮 默认 是显示的
  bool needHideAddMidwayButton = false;
  bool isReorderable = false;
  bool hasShowedActionBar = false;

  late Worker worker;

  List<String> reportedEventNames = [];

  @override
  void initState() {
    super.initState();

    widget.viewModel.firstRespInputItemGetter = () {
      InputItem? firstResp;
      for (var item in inputItems) {
        if (item.isFirstResponder) {
          firstResp = item;
        }
      }
      return firstResp;
    };

    widget.viewModel.isEndPointGetter = () {
      var idx = _currentInputItemIndex();
      return idx == inputItems.length - 1;
    };

    if (widget.searchConfig.cursorLocation == CursorLocation.newMidway) {
      inputItems.add(InputItem(location: widget.searchConfig.location));
    }

    needHideAddMidwayButton = widget.searchConfig.needHideAddMidwayButton;

    inputItems.addAll(widget.searchConfig.initPoints?.map((e) {
          POISearchCellViewModel vm =
              POISearchCellViewModel(e, widget.searchConfig);
          return InputItem(location: e.castPOILocation(), poi: vm);
        }).toList() ??
        []);

    if (inputItems.isEmpty) {
      inputItems.add(InputItem(location: widget.searchConfig.location));
    }

    if (!widget.searchConfig.isAirportEndPoint) {
      if (inputItems.length > 1) {
        switch (widget.searchConfig.cursorLocation) {
          case CursorLocation.newMidway:
          case CursorLocation.firstPoi:
            inputItems.first.isFirstResponder = true;
            break;
          case CursorLocation.endPoi:
            inputItems.last.isFirstResponder = true;
        }
      } else {
        inputItems.first.isFirstResponder = true;
      }
    } else {
      inputItems.first.isFirstResponder = true;
    }

    worker = ever(widget.viewModel.currentSelectedModel, (value) {
      currentSelectedModelChanged(value);
    });

    _updateItemValues();
    _onSearchConditionChanged(inputItems.first);
  }

  currentSelectedModelChanged(POISearchCellViewModel value) {
    var idx = _currentInputItemIndex();
    logPOISearchDebug(
        '终点选择：新增一个点:${value.jsonOutput(false).toString()}, index=$idx');

    /// value基本校验
    if (!value.isValid) {
      logPOISearchDebug('选择的点位不合法，缺少经纬度');
      return;
    }

    if (idx == inputItems.length - 1) {
      if (widget.searchConfig.isUserActionDisabledForEnd) {
        logPOISearchDebug('不允许修改终点');
        return;
      }
    } else {
      if (widget.searchConfig.isUserActionDisabledForVia) {
        logPOISearchDebug('不允许修改途径点');
        return;
      }
    }

    var pre = inputItems.safeAccess(idx - 1);
    if (pre != null) {
      if (isLocationValidAndNotEqual(pre.poi, value)) {
        logPOISearchDebug('相邻两点不能相同：前一个点');
        EasyLoading.showToast('相邻两点不能相同');
        return;
      }
    }
    var next = inputItems.safeAccess(idx + 1);
    if (next != null) {
      if (isLocationValidAndNotEqual(next.poi, value)) {
        logPOISearchDebug('相邻两点不能相同：后一个点');
        EasyLoading.showToast('相邻两点不能相同');
        return;
      }
    }

    final item = inputItems[idx];
    item.changePoi(value);
    _updateItemValues();

    final pois = inputItems.compactMap((p0) => p0.poi).toList();
    widget.viewModel.currentPois = pois.length;

    if (idx != inputItems.length - 1) {
      if ((item.keyword ?? '').isNotEmpty) {
        if (idx == 0) {
          T3Track.trackEventName('019900800001502');
        } else if (idx == 1) {
          T3Track.trackEventName('019900800001702');
        } else if (idx == 2) {
          T3Track.trackEventName('019900800001902');
        }
      }
    }

    if (inputItems.length == 1) {
      final pois = inputItems.compactMap((p0) => p0.poi).toList();
      if (pois.isNotEmpty) {
        logPOISearchDebug('选择结束：回调给页面返回结果');
        widget.onFinishSelection(pois);
      }
    }
  }

  bool isLocationValidAndNotEqual(
      POISearchCellViewModel? left, POISearchCellViewModel? right) {
    var leftLocation = left?.realLocation;
    var rightLocation = right?.realLocation;
    if (leftLocation != null && rightLocation != null) {
      if (LatLng.isLatLngValid(leftLocation) &&
          LatLng.isLatLngValid(rightLocation)) {
        var leftLat = leftLocation.lat.toStringAsFixed(6);
        var leftLng = leftLocation.lng.toStringAsFixed(6);
        var rightLat = rightLocation.lat.toStringAsFixed(6);
        var rightLng = rightLocation.lng.toStringAsFixed(6);
        if (leftLat == rightLat && leftLng == rightLng) {
          return true;
        }
      }
    }
    return false;
  }

  @override
  void dispose() {
    logPOISearchDebug('搜索bar销毁');
    worker.dispose();
    for (var element in inputItems) {
      element.focusNode.dispose();
    }
    super.dispose();
  }

  _updateItemValues() {
    if (hasShowedActionBar) {
      isActionBarHidden = false;
      logPOISearchDebug('isActionBarHidden1 = $isActionBarHidden');
    } else {
      isActionBarHidden = inputItems.length == 1;
      logPOISearchDebug('isActionBarHidden2 = $isActionBarHidden, inputItems=${inputItems.length}');
    }
    isAddMidwayButtonEnabled = inputItems.length != InputConst.kMaxInputItem;

    int index = 1;
    for (var element in inputItems) {
      element.poiType = T3POIType.via;
      element.placeholder = "输入途经点$index";
      element.dotImageName = "assets/images/icon_taxiflow_approach$index.webp";
      element.dotColor = null;
      element.margin = EdgeInsets.zero;
      element.isDeleteButtonHidden = inputItems.length == 1;
      // 需要隐藏 添加途经点 按钮 或者 已经显示了 下方的actionBar
      element.isAddMidWayButtonHidden =
          needHideAddMidwayButton || !isActionBarHidden;
      element.isReorderButtonHidden = inputItems.length <= 2;
      exposureVia(index - 1);
      index++;
    }
    inputItems.last.poiType = T3POIType.end;
    inputItems.last.placeholder = T3POIType.end.placeholder();
    inputItems.last.dotColor =
        T3POIType.via.dotColor(widget.searchConfig.style);
    inputItems.last.dotImageName = null;
    inputItems.last.margin = EdgeInsets.only(
        right: InputConst.kInputItemRightMarginWhenNoDeleteButton);
    inputItems.last.isDeleteButtonHidden = !(inputItems.length > 1);
    setState(() {});
  }

  _onSearchConditionChanged(InputItem item) {
    final condition = item.generateCondition(widget.searchConfig);
    widget.onSearchConditionDidChanged(condition);
  }

  int _currentInputItemIndex() {
    final index =
        max(0, inputItems.indexWhere((element) => element.isFirstResponder));
    return index;
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        SizedBox(
          height: inputItems.length *
              (InputConst.kInputItemHeight + InputConst.kInputItemBottomMargin),
          child: ReorderableListView(
            padding: EdgeInsets.zero,
            children: _inputItemViews(),
            proxyDecorator:
                (Widget child, int index, Animation<double> animation) {
              return child;
            },
            onReorder: (int oldIndex, int newIndex) {
              T3Track.trackEventName('019900800002002');
              if (oldIndex < newIndex) {
                newIndex -= 1;
              }
              var child = inputItems.removeAt(oldIndex);
              inputItems.insert(newIndex, child);
              _updateItemValues();
            },
          ),
        ),
        if (!isActionBarHidden) _actionBar(),
      ],
    );
  }

  void onceReport(String event) {
    if (reportedEventNames.contains(event)) {
      return;
    }
    logPOISearchDebug('onceReport: $event');
    reportedEventNames.add(event);
    T3Track.trackEventName(event);
  }
}

extension _Action on _T3MultiInputBoardState {
  List<Widget> _inputItemViews() {
    return inputItems.map((e) {
      return Container(
        key: Key(e.id),
        height: InputConst.kInputItemHeight,
        margin:
            const EdgeInsets.only(bottom: InputConst.kInputItemBottomMargin),
        child: T3KeywordInputItemWidget(
          textGetter: () {
            return e.displayText();
          },
          searchConfig: widget.searchConfig,
          focusNode: e.focusNode,
          placeholder: e.placeholder,
          dotColor: e.dotColor,
          dotImageName: e.dotImageName,
          cityName: e.cityName(),
          isAddMidWayButtonHidden: e.isAddMidWayButtonHidden,
          isDeleteButtonHidden: e.isDeleteButtonHidden,
          isFirstResponder: e.isFirstResponder,
          isReorderButtonHidden: e.isReorderButtonHidden,
          onAddMidWayButtonTapped: () {
            T3Track.trackEventName('019900800001102');
            _onAddViaClicked(e);
          },
          onDeleteButtonTapped: () {
            inputItems.removeWhere((element) => element.id == e.id);
            _updateItemValues();
          },
          onCityTapped: () {
            if (widget.searchConfig.isStartPoint) {
              T3Track.trackEventName('019900600000102');
            } else {
              T3Track.trackEventName('019900800000102');
            }
            final condition = e.generateCondition(widget.searchConfig);
            var result =
                BoostNavigator.instance.push('cityPickerPage', arguments: {
              'hintText':
                  e.poiType == T3POIType.end ? "请输入您的目的地城市" : "请输入您途径的城市",
              'cityScope': widget.searchConfig.cityScope.value,
              'autoPop': true,
              'showBack': widget.searchConfig.showBackButton,
              'isFromFlutter': true,
            });
            result.then((value) {
              if (value != null) {
                var body = value as Map?;
                if (body != null) {
                  var result = body['result'];
                  if (result == 'data') {
                    var cityData = body['data'];
                    if (cityData != null) {
                      var city = HostModel.fromJson(cityData);
                      logPOISearchDebug('搜索框切换城市：${city.toJson().toString()}');
                      didChangeCity(condition, city, e);
                    }
                  }
                }
              }
              if (widget.searchConfig.isAirportEndPoint) {
                return;
              }
              Future.delayed(const Duration(milliseconds: 100), () {
                FocusScope.of(context).requestFocus(e.focusNode);
              });
            });
          },
          onTextChanged: (value) {
            e.changeKeyword(value);
            e.isFirstResponder = true;
            _onSearchConditionChanged(e);
          },
          onBecomeFirstResponder: () {
            for (var element in inputItems) {
              element.isFirstResponder = false;
            }
            e.isFirstResponder = true;
            didClickVia();
            // 如果当前点击的是终点 并且 是送机的场景  需要弹出弹窗
            // cityInfo 只需要 cityCode adCode city 等参数
            if (widget.searchConfig.isAirportEndPoint && e == inputItems.last) {
              widget.airportCityChangeCallback(e.generateHostModel(), e);
            }
            _onSearchConditionChanged(e);
          },
        ),
      );
    }).toList();
  }

  didChangeCity(T3SearchCondition condition, HostModel city, InputItem item) {
    if (widget.searchConfig.isAirportEndPoint) {
      widget.airportCityChangeCallback(city, item);
    } else {
      condition.updateCity(city);
      widget.onSearchConditionDidChanged(condition);
      item.changeCity(city);
      setState(() {});
    }
  }

  didClickVia() {
    var index = _currentInputItemIndex();
    if (index == 0) {
      T3Track.trackEventName('019900800001402');
      return;
    } else if (index == 1) {
      T3Track.trackEventName('019900800001602');
      return;
    } else if (index == 2) {
      T3Track.trackEventName('019900800001802');
      return;
    }
  }

  exposureVia(int index) {
    if (index == 0) {
      T3Track.trackEventName('019900800001401');
      return;
    } else if (index == 1) {
      T3Track.trackEventName('019900800001601');
      return;
    } else if (index == 2) {
      T3Track.trackEventName('019900800001801');
      return;
    }
  }
}

extension _ActionBar on _T3MultiInputBoardState {
  Widget _actionBar() {
    hasShowedActionBar = true;
    onceReport('019900800001201');
    onceReport('019900800001301');
    return Container(
      height: 46,
      margin: const EdgeInsets.only(bottom: InputConst.kInputItemBottomMargin),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Flexible(
            flex: 1,
            child: T3GestureDetector(
                onTap: () {
                  _onAddViaClicked(inputItems[_currentInputItemIndex()]);
                },
                child: Container(
                  height: 34,
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                      borderRadius: const BorderRadius.all(Radius.circular(17)),
                      border: Border.all(
                          width: 0.5,
                          color: isAddMidwayButtonEnabled
                              ? const Color(0xFF02102A)
                              : const Color(0xFFB7BECC))),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      if (isAddMidwayButtonEnabled)
                        T3Image.t3assets(T3AssetsName.icon_add),
                      if (!isAddMidwayButtonEnabled)
                        T3Image.t3assets(T3AssetsName.icon_add_gray),
                      Text(
                        "添加途经点",
                        style: TextStyle(
                            fontSize: 12,
                            fontWeight: FontWeight.w500,
                            color: isAddMidwayButtonEnabled
                                ? const Color(0xFF02102A)
                                : const Color(0xFFB7BECC)),
                      )
                    ],
                  ),
                )),
          ),
          const SizedBox(
            width: 24,
          ),
          Flexible(
            flex: 1,
            child: T3GestureDetector(
                onTap: _onDoneClicked,
                child: Container(
                  height: 34,
                  alignment: Alignment.center,
                  decoration: const BoxDecoration(
                      color: Color(0xFF00AD59),
                      borderRadius: BorderRadius.all(Radius.circular(17))),
                  child: const Text(
                    "完成",
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 12,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                )),
          ),
        ],
      ),
    );
  }

  _onAddViaClicked(InputItem item) {
    if (!isAddMidwayButtonEnabled) {
      return;
    }
    T3Track.trackEventName('019900800001202');
    final index =
        max(0, inputItems.indexWhere((element) => element.id == item.id));

    var newItem = InputItem(location: widget.searchConfig.location);
    inputItems.insert(index, newItem);
    for (var element in inputItems) {
      element.isFirstResponder = false;
    }
    newItem.isFirstResponder = true;
    isActionBarHidden = false;
    _updateItemValues();
    Future.delayed(const Duration(milliseconds: 100), () {
      FocusScope.of(context).requestFocus(newItem.focusNode);
    });
  }

  _onDoneClicked() {
    T3Track.trackEventName('019900800001302');
    final pois = inputItems.compactMap((p0) => p0.poi).toList();
    if (pois.isEmpty) {
      EasyLoading.showToast('请输入地点信息');
      return;
    }
    logPOISearchDebug(
        '点击完成按钮：${pois.map((e) => e.jsonOutput(false).toString()).toList().toString()}');
    widget.onFinishSelection(pois);
  }
}
